def max_forward_matching(sentence, dictionary):
    """
    max forward matching
    :param sentence: variable name to be splitted
    :param dictionary: a set containing all words
    :return: results of splitted words
    """

    result = []  # 存储分词结果
    index = 0  # 当前处理的位置
    sentence_length = len(sentence)  # 句子长度

    while index < sentence_length:
        max_word = sentence[index]  # 当前最大词
        matched = False
        for size in range(1, sentence_length - index + 1):
            word = sentence[index:index + size]
            if word in dictionary:
                max_word = word
                matched = True
        if matched:
            print(result, max_word)
            result.append(max_word)
        else:
            print("not matched for character", max_word)
        index += len(max_word)

    return result


with open("./words/en.txt") as f:
    dictionary = set(line.strip() for line in f.readlines())
# 示例
dictionary.update({"pool", "id", "transform", "ip", "rru", 'i', 'q',
                   'data', 'datai', 'dataq', 'frequency', 'hz', 'khz', 'freq', 'ul', 'asic'})
sentence = "poolidtransformiprrmdataqfreqkhz"
result = max_forward_matching(sentence, dictionary)
print(result)  # 输出：['pool', 'id', 'transform', 'ip']

sentence = "subpoolid"
result = max_forward_matching(sentence, dictionary)
print(result)  # 输出：['pool', 'id', 'transform', 'ip']

sentence = "subscriptpoolid"
result = max_forward_matching(sentence, dictionary)
print(result)  # 输出：['pool', 'id', 'transform', 'ip']

sentence = "subscriptpoolid"
result = max_forward_matching(sentence, dictionary)
print(result)  # 输出：['pool', 'id', 'transform', 'ip']

sentence = "ulasicid"
result = max_forward_matching(sentence, dictionary)
print(result)  # 输出：['pool', 'id', 'transform', 'ip']

sentence = "ulsubchipid"
result = max_forward_matching(sentence, dictionary)
print(result)  # 输出：['pool', 'id', 'transform', 'ip']

sentence = "ulpoolid"
result = max_forward_matching(sentence, dictionary)
print(result)  # 输出：['pool', 'id', 'transform', 'ip']